#pragma once

#include <QDebug>
#include <QSettings>
#include <QString>

enum Edition { SIMPLE, FLAGSHIP };

enum Upgrade { SUCCESS = 0, RUNNING, FAILED, INIT };

Q_DECLARE_METATYPE(Upgrade)

class MSettings : public QObject {
    Q_OBJECT

    QSettings* m_default;

public:
    enum INI { S_DEFAULT, RELEASE };
    Q_ENUM(INI)

public:
    explicit MSettings(QObject* parent = nullptr);
    MSettings(const MSettings&) = delete;
    MSettings(MSettings&&) = delete;
    static void setNoOutput();

    static QSettings* sets(MSettings::INI ini);

public:
    template <class T, class T2>
    inline static T2 value(const T& key, T2 defaultValue,
                           MSettings::INI ini = MSettings::S_DEFAULT) {
        QSettings* p = sets(ini);
        QVariant val = p->value(key);
        if (val.isNull()) {
            p->setValue(key, defaultValue);  // 设置默认值
            return defaultValue;
        }

        return val.value<T2>();
    }

    template <class T>
    inline static QString value(const T& key, const char* defaultValue = "",
                                MSettings::INI ini = S_DEFAULT) {
        QSettings* p = sets(ini);
        p->sync();
        QVariant val = p->value(key);
        if (val.isNull()) {
            p->setValue(key, defaultValue);  // 设置默认值
            return defaultValue;
        }

        return val.toString();
    }

    template <class T, class T2>
    inline static void setValue(const T& key, T2 newValue,
                                MSettings::INI ini = S_DEFAULT) {
        QSettings* p = sets(ini);
        p->setValue(key, newValue);
        p->sync();  // 确保写入操作尽快刷新到磁盘
    }
};
